package com.p2p.auth.controller.api.crm;


import com.p2p.auth.common.base.JsonResult;
import com.p2p.auth.common.base.ProcessAPI;
import com.p2p.auth.common.base.ResponseBase;
import com.p2p.auth.common.base.ResultCode;
import com.p2p.auth.controller.Routes;
import com.p2p.auth.domain.entity.User;
import com.p2p.auth.service.specification.UserSpecification;
import com.p2p.auth.service.lifeCycle.UserUtils;
import com.p2p.auth.service.repository.UserRepository;
import com.p2p.auth.service.ExcelService;
import com.p2p.auth.domain.dto.user.UserQueryDTO;
import com.p2p.auth.domain.dto.user.UserResponseDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by lipei on 2017/4/18.
 */

@RestController
@Api(value = "用户API", description = "用户的CRUD操作，注意必传参数与参数")
public class CrmUserController {
    public static final String USER_NAME = null;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserRepository userRepository;



    @ApiOperation(value = "查询所有用户", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.CRM_USER_ALL, method = RequestMethod.GET)
    public JsonResult getAllUser(HttpServletRequest request, UserQueryDTO req) {

        ProcessAPI api = (result, validate) -> {
            Specification<User> specification = UserSpecification.buildFromDTO(req);
            Page<User> userPage = userRepository.findAll(specification,req.getPage());
            List<UserResponseDTO> userRespList = new ArrayList<>();
            userPage.forEach(l -> {
                UserResponseDTO dto = UserUtils.copyToDTO(l);
                userRespList.add(dto);
            });
            result.setResult(userRespList);
            result.setSize(userPage.getTotalElements());

        };
        return api.process(request);
    }

    @ApiOperation(value = "修改用户基本信息", notes = "输入userId修改userName(角色详情可选传)", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userId", value = "用户ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "path", name = "userName", value = "用户名称", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "userAge", value = "用户描述", dataType = "String")

    })
    @RequestMapping(value =Routes.CRM_USER_UPD, method = RequestMethod.PUT)
    public ResponseBase<UserResponseDTO> updateUserNameUserDescription(@PathVariable(value = "userId") String userId, @PathVariable(value = "userName") String userName, @RequestParam String userAge) {
        ResponseBase<UserResponseDTO> result = new ResponseBase<>();

        if (StringUtils.isEmpty(userId)) {
            result.setMsg("The given userId must not be null!");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }
        if (StringUtils.isEmpty(userName)) {
            result.setMsg("The given userName must not be null!");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        User po = userRepository.findByUserId(userId);
        if (null == po) {
            result.setMsg("The given user Object must not be null!");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }
        po.setRealName(userName);


        if (userAge != null) {
            po.setAge(Integer.valueOf(userAge));
        }
        po.setLastUpdated(Date.from(Instant.now()));
        User updatePO = userRepository.save(po);

        UserResponseDTO dto = UserUtils.copyToDTO(updatePO);

        result.setResultCode(ResultCode.SUCC.getCode());
        result.setMsg("success");
        result.setResult(dto);
        return result;
    }

    @ApiOperation(value = "导出用户列表", notes = "导出用户列表", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.CRM_USER_EXCEL, method = RequestMethod.GET)
    public void excel(HttpServletResponse response, UserQueryDTO req){
        Specification<User> specification = UserSpecification.buildFromDTO(req);
        Page<User> userPage = userRepository.findAll(specification,req.getPage());
        List<UserResponseDTO> userRespList = new ArrayList<>();
        userPage.forEach(l -> {
            UserResponseDTO dto = UserUtils.copyToDTO(l);
            userRespList.add(dto);
        });

        LinkedHashMap<String, String> struct = new LinkedHashMap<>();
        struct.put("realName", "姓名");
        struct.put("phoneNum", "手机号码");
        struct.put("balance", "账户余额");
        struct.put("rebate", "累计返利（已返利金额）");
        struct.put("age", "年纪");
        struct.put("marketingAmonut", "累计营销费用");
        struct.put("invitePhoneNum", "邀请人手机号");
        struct.put("tieCard", "是否绑卡");
        struct.put("channelName", "渠道来源");
        struct.put("remark", "备注");
        struct.put("status", "状态");

        ExcelService excelService = new ExcelService(userRespList, struct);
        excelService.exportToStream(response, "用户列表");

    }

    @ApiOperation(value = "根据手机号获取单一用户信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.CRM_USER_GET_BY_PHONENUM, method = RequestMethod.GET)
    public ResponseBase<UserResponseDTO> getInfoByPhoneNum(@RequestParam String phoneNum) {
        ResponseBase<UserResponseDTO> result = new ResponseBase<>();
        if (StringUtils.isEmpty(phoneNum)) {
            result.setMsg("The given phoneNum must not be null!");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        User po = userRepository.findByPhoneNum(phoneNum);
        if (null == po) {
            result.setMsg("The given User must not be null!");
            result.setResultCode(ResultCode.NO_DATA.getCode());
            return result;
        }

        UserResponseDTO dto = UserUtils.copyToDTO(po);
        result.setResultCode(ResultCode.SUCC.getCode());
        result.setMsg("success");
        result.setResult(dto);
        return result;
    }

    @ApiOperation(value = "根据userId获取单一用户信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.CRM_USER_GET_BY_USERID, method = RequestMethod.GET)
    public ResponseBase<UserResponseDTO> getInfoByUserId(@RequestParam String userId) {
        ResponseBase<UserResponseDTO> result = new ResponseBase<>();
        if (StringUtils.isEmpty(userId)) {
            result.setMsg("The given phoneNum must not be null!");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        User po = userRepository.findByUserId(userId);
        if (null == po) {
            result.setMsg("The given User must not be null!");
            result.setResultCode(ResultCode.NO_DATA.getCode());
            return result;
        }

        UserResponseDTO dto = UserUtils.copyToDTO(po);
        result.setResultCode(ResultCode.SUCC.getCode());
        result.setMsg("success");
        result.setResult(dto);
        return result;

    }

}
